package com.zb.callback.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zb.callback.entity.HoubanyunConstant;
import com.zb.callback.service.impl.vo.Status;
import com.zb.callback.utils.HoubanyunFaultDetailFieldMappingUtil;
import com.zb.constant.WorkConstant;
import com.zb.entity.*;
import com.zb.extend.WorkFinishOrderTemplateFieldValExtend;
import com.zb.http.HttpClientUtil;
import com.zb.mapper.ZjWorkOrderMapper;
import com.zb.service.*;
import com.zb.view.ViewNetworkEmpAccount;
import com.zb.yaml.HoubanYunOrder;
import com.zb.yaml.HoubanYunSecret;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Stream;

/**
 * @Author WEN
 * @Date 2024/8/25 0025
 **/
@Log4j2
@Service
public class LKaiPushServiceImpl {
    private static LKaiPushServiceImpl lKaiPushService;

    @PostConstruct
    public void init() {
        lKaiPushService = this;
    }

    @Resource(name = "asyncServiceExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Resource
    private ZjWorkHoubanYunRelationService workHoubanYunRelationService;
    @Resource
    private ZjWorkOrderService workOrderService;
    @Resource
    private ZjWorkDispatchNetworkService workDispatchNetworkService;
    @Resource
    private ZjWorkDispatchEngineerService workDispatchEngineerService;
    @Resource
    private ZjWorkModuleService workModuleService;
    @Resource
    private ZjWorkDetailService workDetailService;
    @Resource
    private ZjWorkFinishOrderTemplateFieldValService workFinishOrderTemplateFieldValService;
    @Resource
    private ZjWorkHoubanYunPushResultService workHoubanYunPushResultService;
    @Resource
    private ViewNetworkEmpAccountService viewNetworkEmpAccountService;
    @Autowired
    private ZjWorkOrderMapper zjWorkOrderMapper;

    // 工单状态推送
    public static void pushOrderStatus(Long workId) {
        pushOrder(workId);
    }

    // 工单状态推送
    public static void pushOrderStatus(List<Long> workIds) {
        for (Long workId : workIds) {
            pushOrder(workId);
        }
    }

    private static void pushOrder(Long workId) {
        ZjWorkHoubanYunRelation houbanYunRelation = lKaiPushService.workHoubanYunRelationService.getById(workId);
        if (null == houbanYunRelation) {
            return;
        }
        ZjWorkOrder order = lKaiPushService.workOrderService.getById(workId);
        ZjWorkDetail detail = lKaiPushService.workDetailService.getById(order.getId());
        Integer statusId = null; // 已上门
        String reservationDate = null; // 预约时间
        String orderEndTime = null; // 工单完成时间
        Integer approach =  order.getApproach(); //处理方式
        Integer isWorkAgain =  order.getIsWorkAgain(); //是否需要再次上门
        String workAgainMsg =  order.getWorkAgainMsg(); //再次上门的原因
        String signImage =  order.getSignImage(); //签单图
        Integer serviceStatus = order.getCancelReason(); //取消原因

        // 待服务商确认
//        if (order.getStatus() == WorkConstant.WORK_STATUS_2) {
////            statusId = 12; // 待确认
//        }
        // 工单完成
        if (order.getStatus() == WorkConstant.WORK_STATUS_4) {
            statusId = 14; // 待回访
            orderEndTime = DateFormatUtils.format(order.getEndTime(), "yyyy-MM-dd HH:mm:ss");
            // B端工单（维修）
            if (Objects.equals(HoubanyunConstant.B_TABLE_ID, houbanYunRelation.getTableId())) {
                statusId = 5;
            }
        }
        if (order.getStatus() == WorkConstant.WORK_STATUS_3) {
            ZjWorkDispatchNetwork dispatchNetwork = lKaiPushService.workDispatchNetworkService.getByWorkIdAndNetowrkId(workId, order.getNetworkId());
//            if (dispatchNetwork.getStatus() == WorkConstant.DISPATCH_NETWORK_STATUS_2) {
//                statusId = 1; // 待派工
//            }
            if (dispatchNetwork.getStatus() == WorkConstant.DISPATCH_NETWORK_STATUS_4) {
                ZjWorkDispatchEngineer dispatchEngineer = lKaiPushService.workDispatchEngineerService.getByNetworkEmpIdAndWorkId(order.getNetworkEmpId(), workId);
                if (order.getIsCall() == 1) {
                    statusId = 3; // 待服务
                }
                if (dispatchEngineer.getStatus() == WorkConstant.DISPATCH_ENGINEER_STATUS_2) {
//                    if (!dispatchEngineer.getReservation()) {
//                        statusId = 2; // 待预约
//                    }
                    if (!dispatchEngineer.getSignIn() && dispatchEngineer.getReservation()) {
                        if (StringUtils.isNotBlank(dispatchEngineer.getReservationDate()) && StringUtils.isNotBlank(dispatchEngineer.getReservationStartTime())) {
                            reservationDate = dispatchEngineer.getReservationDate().split(" ")[0] + " " + dispatchEngineer.getReservationStartTime().split(" ")[1];
                        }
                    }
                    if (dispatchEngineer.getSignIn()) {
                        statusId = 10; // 已上门
                    }
                }
            }
        }
        // 取消
        if (Objects.equals(HoubanyunConstant.C_TABLE_ID, houbanYunRelation.getTableId())) {
            if (serviceStatus != null) {
                if (serviceStatus.equals(2) || serviceStatus.equals(3)) {
                    statusId = 5; //已完结
                }
            }
        }
        // 工单状态
        Map<String, Object> feildMap = new HashMap<>();
        Map<String, Object> feildMap2 = new HashMap<>();
        if (null != statusId) {
            Map<String, Object> statusIdMap = new HashMap<>();
            statusIdMap.put("id", statusId);
            // C端工单（安装、维修）
            if (Objects.equals(HoubanyunConstant.C_TABLE_ID, houbanYunRelation.getTableId())) {
                feildMap.put("2200000469555673", statusIdMap);
            }
            // B端工单（维修）
            if (Objects.equals(HoubanyunConstant.B_TABLE_ID, houbanYunRelation.getTableId())) {
                feildMap.put("2200000464559693", statusIdMap);
            }
        }
        //服务受理状态
        if (serviceStatus != null) {
            Map<String, Object> serviceStatusMap = new HashMap<>();
            serviceStatusMap.put("id", serviceStatus);
            // C端工单（安装、维修）
            if (Objects.equals(HoubanyunConstant.C_TABLE_ID, houbanYunRelation.getTableId())) {
                feildMap.put("2200000469555696", serviceStatusMap); // 服务受理状态
            }
        }
        //处理方式
        if (approach != null) {
            Map<String, Object> approachMap = new HashMap<>();
            approachMap.put("id", approach);
            // C端工单（安装、维修）
            if (Objects.equals(HoubanyunConstant.C_TABLE_ID, houbanYunRelation.getTableId())) {
                feildMap.put("2200000469555697", approachMap); // 处理方式
            }
        }
        //签单图片
        if (signImage != null) {
            // C端工单（安装、维修）
            if (Objects.equals(HoubanyunConstant.C_TABLE_ID, houbanYunRelation.getTableId())) {
                feildMap.put("2200000505822851", signImage); // 签单图片
            }
        }
        //是否需要再次上门
        if (isWorkAgain != null) {
            // C端工单（安装、维修）
            Map<String, Object> isWorkAgainMap = new HashMap<>();
            isWorkAgainMap.put("id", isWorkAgain);
            if (Objects.equals(HoubanyunConstant.C_TABLE_ID, houbanYunRelation.getTableId())) {
                feildMap.put("2200000469555724", isWorkAgainMap); // 是否需要再次上门
            }
        }
        //再次上门原因
        if (workAgainMsg != null) {
            // C端工单（安装、维修）
            if (Objects.equals(HoubanyunConstant.C_TABLE_ID, houbanYunRelation.getTableId())) {
                feildMap.put("2200000469555725", workAgainMsg); // 再次上门原因
            }
        }
        // 再查询
        order = lKaiPushService.workOrderService.getById(workId);
        if (order.getSignTime() != null && order.getCommentTime() != null && order.getIsYsm() == null){
            String reservationStartTime = DateUtil.format(order.getSignTime(), "yyyy-MM-dd HH:mm:ss"); //开始
            String reservationEndTime = DateUtil.format(order.getCommentTime(), "yyyy-MM-dd HH:mm:ss"); //结束
            //上门开始结束时间
            if (reservationStartTime != null) {
                // C端工单（安装、维修）
                if (Objects.equals(HoubanyunConstant.C_TABLE_ID, houbanYunRelation.getTableId())) {
                    feildMap2.put("2200000469563210", reservationStartTime); // 上门开始时间
                }
            }
            if (reservationEndTime != null) {
                // C端工单（安装、维修）
                if (Objects.equals(HoubanyunConstant.C_TABLE_ID, houbanYunRelation.getTableId())) {
                    feildMap2.put("2200000469563211", reservationEndTime); // 上门结束时间
                }
            }
            if (order.getCode() != null) {
                // C端工单（安装、维修）
                if (Objects.equals(HoubanyunConstant.C_TABLE_ID, houbanYunRelation.getTableId())) {
                    feildMap2.put("2200000513455684", order.getCode()); // 工单编号
                }
            }
            ZjWorkOrder zjWorkOrder1 = new ZjWorkOrder();
            zjWorkOrder1.setId(order.getId());
            zjWorkOrder1.setIsYsm(1);
            lKaiPushService.zjWorkOrderMapper.updateById(zjWorkOrder1);
        } else if (order.getSignTime() != null && order.getJdTime() != null){
            if (order.getIsYsm() == null || order.getIsYsm() != 2) {
                String reservationStartTime = DateUtil.format(order.getSignTime(), "yyyy-MM-dd HH:mm:ss"); //开始
                String reservationEndTime = DateUtil.format(order.getJdTime(), "yyyy-MM-dd HH:mm:ss"); //结束
                //上门开始结束时间
                if (reservationStartTime != null) {
                    // C端工单（安装、维修）
                    if (Objects.equals(HoubanyunConstant.C_TABLE_ID, houbanYunRelation.getTableId())) {
                        feildMap2.put("2200000469563210", reservationStartTime); // 上门开始时间
                    }
                }
                if (reservationEndTime != null) {
                    // C端工单（安装、维修）
                    if (Objects.equals(HoubanyunConstant.C_TABLE_ID, houbanYunRelation.getTableId())) {
                        feildMap2.put("2200000469563211", reservationEndTime); // 上门结束时间
                    }
                }
                if (order.getCode() != null) {
                    // C端工单（安装、维修）
                    if (Objects.equals(HoubanyunConstant.C_TABLE_ID, houbanYunRelation.getTableId())) {
                        feildMap2.put("2200000513455684", order.getCode()); // 工单编号
                    }
                }
                ZjWorkOrder zjWorkOrder2 = new ZjWorkOrder();
                zjWorkOrder2.setId(order.getId());
                zjWorkOrder2.setIsYsm(2);
                lKaiPushService.zjWorkOrderMapper.updateById(zjWorkOrder2);
            }
        }
        //预约上门时间
        if (null != reservationDate) {
            // C端工单（安装、维修）
            if (Objects.equals(HoubanyunConstant.C_TABLE_ID, houbanYunRelation.getTableId())) {
                feildMap.put("2200000469555709", reservationDate); // 预约上门时间
            }
            // B端工单（维修）
            if (Objects.equals(HoubanyunConstant.B_TABLE_ID, houbanYunRelation.getTableId())) {
                feildMap.put("2200000464559713", reservationDate); // 预约上门时间
            }
        }
        // 工单完成时间
        if (null != orderEndTime) {
            ZjWorkModule workModule = lKaiPushService.workModuleService.getById(order.getModuleId());
            // B端工单结单字段
            if (Objects.equals(HoubanyunConstant.B_TABLE_ID, houbanYunRelation.getTableId())) {
                feildMap.put("2200000464559723", orderEndTime); // 工单完结时间#
                // 维修
                if (workModule.getType() == 2) {
                    getBUpdateFinishField(houbanYunRelation.getId(), feildMap);
                }
            }
            // C端工单结单字段
            if (Objects.equals(HoubanyunConstant.C_TABLE_ID, houbanYunRelation.getTableId())) {
                feildMap.put("2200000469555728", orderEndTime); // 服务完成时间
                // 工程师
                ViewNetworkEmpAccount empAccount = lKaiPushService.viewNetworkEmpAccountService.getById(order.getNetworkEmpId());
                feildMap.put("2200000489379244", empAccount.getName()); // 师傅姓名
                feildMap.put("2200000489379245", empAccount.getPhone()); // 师傅联系电话

                // 安装
                if (workModule.getType() == 1) {
                    getCInstallFinishField(houbanYunRelation.getId(), feildMap);
                }
                // 维修
                if (workModule.getType() == 2) {
                    getCUpdateFinishField(houbanYunRelation.getId(), feildMap);
                }
            }
        }
        order.setThirdPushState(1);//默认为1
        Map<String, Object> paramMap = new HashMap<>();
        Map<String, Object> paramMap2 = new HashMap<>();
        paramMap.put("fields", feildMap);
        paramMap2.put("table_id", "2100000057235247");
        paramMap2.put("fields", feildMap2);
        String url = "https://api.huoban.com/openapi/v1/item/" + houbanYunRelation.getItemId();
        String url2 = "https://api.huoban.com/openapi/v1/item";
        // 封装请求头
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Open-Authorization", HoubanYunSecret.getApiKey()); // appKey
        log.info("============================== 反写开始 ===============================================");
        log.info("乐开反写的数据：{}，{}", url, JSON.toJSONString(paramMap));
        String put = HttpClientUtil.put(url, headerMap, paramMap);
        HttpClientUtil.post(url2, headerMap, paramMap2);
        JSONObject postObj = JSON.parseObject(put, JSONObject.class);
        log.info("乐开反写结果：{}", postObj.toJSONString());
        if (null != statusId && statusId == 5) {
            log.info("乐开结单反写结果：{}", postObj.toJSONString());
        }
        log.info("============================== 反写结束 ===============================================");
        int tryCount = 10; // 重试次数
        if (postObj.getInteger("code") != 0) {
            order.setThirdPushState(0);//失败为0
            order.setThirdPushErrorMsg(postObj.toJSONString());
            boolean stop = false;
            while (!stop) {
                if (tryCount == 0) {
                    pushResultLog(order, houbanYunRelation.getItemId(), statusId, JSON.toJSONString(paramMap), 0, postObj.toJSONString());
                    stop = true;
                }
                put = HttpClientUtil.post(url, paramMap);
                postObj = JSON.parseObject(put, JSONObject.class);
                if (postObj.getInteger("code") == 0) {
                    order.setThirdPushState(1);
                    pushResultLog(order, houbanYunRelation.getItemId(), statusId, JSON.toJSONString(paramMap), 1, postObj.toJSONString());
                    stop = true;
                    return;
                }
                tryCount--;
                // 间隔五秒推送一次
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {

                }
            }
        } else {
            pushResultLog(order, houbanYunRelation.getItemId(), statusId, JSON.toJSONString(paramMap), 1, postObj.toJSONString());
        }
        order.setThirdPushMsg(postObj.toJSONString());
        order.setThirdStateFinishContentJson(JSON.toJSONString(paramMap));
        lKaiPushService.workOrderService.updateById(order);
    }

    private static void pushResultLog(ZjWorkOrder order, String itemId, Integer pushType, String pushData, Integer pushResultType, String pushResult) {
        ZjWorkHoubanYunPushResult pushResultBean = new ZjWorkHoubanYunPushResult()
                .setId(IdWorker.getId())
                .setCustAccId(order.getCustAccId())
                .setWorkId(order.getId())
                .setWorkNo(order.getCode())
                .setItemId(itemId)
                .setPushType(pushType)
                .setPushTypeName(null != pushType ? (pushType == 5 ? "已完结" : pushType == 10 ? "已上门" : null) : null)
                .setPushData(pushData)
                .setPushResultType(pushResultType)
                .setPushResult(pushResult);
        lKaiPushService.workHoubanYunPushResultService.save(pushResultBean);
    }

    /**
     * 获取B端维修工单结单字段
     *
     * @param workId   工单ID
     * @param feildMap
     */
    private static void getBUpdateFinishField(Long workId, Map<String, Object> feildMap) {
        List<String> models = new ArrayList<>(); // 产品型号
        List<String> faultResons = new ArrayList<>(); // 故障原因
        List<String> faultDetails = new ArrayList<>(); // 故障明细
        List<String> faultImages = new ArrayList<>(); // 现场故障图片
        List<String> handlerModes = new ArrayList<>(); // 解决方式
        List<String> updateAftarImages = new ArrayList<>(); // 维修后的图片
        List<WorkFinishOrderTemplateFieldValExtend> extendList = lKaiPushService.workFinishOrderTemplateFieldValService.getPushFieldByWorkIdAndWorkStatementTemplateId(workId, HoubanYunOrder.getbUpdateFinishTemplateId1());
        HoubanyunFaultDetailFieldMappingUtil faultDetail = null;
        for (WorkFinishOrderTemplateFieldValExtend extend : extendList) {
            // 产品型号
            if (Objects.equals(HoubanYunOrder.getbUpdateFinishTemplateFieldId1(), extend.getWorkStatementTemplateFieldId())) {
                models.addAll(extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList());
                continue;
            }
            // 故障明细
            if (Objects.equals(HoubanYunOrder.getbUpdateFinishTemplateFieldId2(), extend.getWorkStatementTemplateFieldId())) {
                for (String val : extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList()) {
                    faultDetail = HoubanyunFaultDetailFieldMappingUtil.getFaultDetail(val);
                    if (null == faultDetail) {
                        continue;
                    }
                    if (StringUtils.isNotBlank(faultDetail.getFaultReson())) {
                        faultResons.add(faultDetail.getFaultReson());
                    } else {
                        faultResons.add("2300012207355499");
                    }
                    if (StringUtils.isNotBlank(faultDetail.getFaultDetail())) {
                        faultDetails.add(faultDetail.getFaultDetail());
                    } else {
                        faultDetails.add("2300013005091923");
                    }
                }
                continue;
            }
            // 现场故障图片
            if (Objects.equals(HoubanYunOrder.getbUpdateFinishTemplateFieldId3(), extend.getWorkStatementTemplateFieldId())) {
                faultImages.addAll(extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList());
                continue;
            }
            // 解决方式
            if (Objects.equals(HoubanYunOrder.getbUpdateFinishTemplateFieldId4(), extend.getWorkStatementTemplateFieldId())) {
                handlerModes.addAll(extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList());
                continue;
            }
            // 维修后的图片
            if (Objects.equals(HoubanYunOrder.getbUpdateFinishTemplateFieldId5(), extend.getWorkStatementTemplateFieldId())) {
                updateAftarImages.addAll(extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList());
                continue;
            }
            // 完工视频
            if (Objects.equals(HoubanYunOrder.getbUpdateFinishTemplateFieldId6(), extend.getWorkStatementTemplateFieldId())) {
//                updateAftarImages.addAll(extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList());
            }
        }
        feildMap.put("2200000478953226", CollectionUtil.isEmpty(models) ? "" : String.join(",", models)); // 维修产品型号
        feildMap.put("2200000464693628", faultResons); // 故障原因
        feildMap.put("2200000464693636", faultDetails); // 故障明细
        feildMap.put("2200000478953106", CollectionUtil.isEmpty(faultImages) ? "" : String.join(",", faultImages)); // 现场故障图片
        feildMap.put("2200000464559720", CollectionUtil.isEmpty(handlerModes) ? "" : String.join(",", handlerModes)); // 解决方式
        feildMap.put("2200000478953107", CollectionUtil.isEmpty(updateAftarImages) ? "" : String.join(",", updateAftarImages)); // 维修后的图片
    }

    /**
     * 获取C端维修工单结单字段
     *
     * @param workId   工单ID
     * @param feildMap
     */
    private static void getCUpdateFinishField(Long workId, Map<String, Object> feildMap) {
        List<String> models = new ArrayList<>(); // 产品型号
        List<String> snCodes = new ArrayList<>(); // 唯一码
        List<String> faultResons = new ArrayList<>(); // 故障原因
        List<String> faultDetails = new ArrayList<>(); // 故障明细
        List<String> faultImages = new ArrayList<>(); // 现场故障图片
        List<String> handlerModes = new ArrayList<>(); // 解决方式
        List<String> updateAftarImages = new ArrayList<>(); // 维修后的图片
        List<WorkFinishOrderTemplateFieldValExtend> extendList = lKaiPushService.workFinishOrderTemplateFieldValService.getPushFieldByWorkIdAndWorkStatementTemplateId(workId, HoubanYunOrder.getcUpdateFinishTemplateId1());
        HoubanyunFaultDetailFieldMappingUtil faultDetail = null;
        for (WorkFinishOrderTemplateFieldValExtend extend : extendList) {
            // 产品型号
            if (Objects.equals(HoubanYunOrder.getcUpdateFinishTemplateFieldId1(), extend.getWorkStatementTemplateFieldId())) {
                models.addAll(extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList());
                continue;
            }
            // 故障明细
            if (Objects.equals(HoubanYunOrder.getcUpdateFinishTemplateFieldId2(), extend.getWorkStatementTemplateFieldId())) {
                for (String val : extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList()) {
                    faultDetail = HoubanyunFaultDetailFieldMappingUtil.getFaultDetail(val);
                    if (null == faultDetail) {
                        continue;
                    }
                    faultResons.add(faultDetail.getFaultReson());
                    faultDetails.add(faultDetail.getFaultDetail());
                }
                continue;
            }
            // 现场故障图片
            if (Objects.equals(HoubanYunOrder.getcUpdateFinishTemplateFieldId3(), extend.getWorkStatementTemplateFieldId())) {
                faultImages.addAll(extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList());
                continue;
            }
            // 解决方式
            if (Objects.equals(HoubanYunOrder.getcUpdateFinishTemplateFieldId4(), extend.getWorkStatementTemplateFieldId())) {
                handlerModes.addAll(extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList());
                continue;
            }
            // 维修后的图片
            if (Objects.equals(HoubanYunOrder.getcUpdateFinishTemplateFieldId5(), extend.getWorkStatementTemplateFieldId())) {
                updateAftarImages.addAll(extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList());
            }
            // 完工视频
            if (Objects.equals(HoubanYunOrder.getcUpdateFinishTemplateFieldId5(), extend.getWorkStatementTemplateFieldId())) {
//                updateAftarImages.addAll(extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList());
            }
            // 唯一码
            if (Objects.equals(HoubanYunOrder.getcUpdateFinishTemplateFieldId7(), extend.getWorkStatementTemplateFieldId())) {
                snCodes.addAll(extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList());
            }
            //判断是否可维修
            if (Objects.equals(HoubanYunOrder.getcUpdateFinishTemplateFieldId10(), extend.getWorkStatementTemplateFieldId())) {
                Optional<String> first = extend.getVals().stream().map(FieldValOptionVo::getOptValue).findFirst();
                Status status = new Status();
                if (first.isPresent()) {
                    String s = first.get();

                    if (s != null && s.equals("无法维修")) {
                        status.setId(2);
                        feildMap.put("2200000470814803", status);
                    } else {
                        status.setId(1);
                        feildMap.put("2200000470814803", status);
                    }
                }
            }
            //新产品型号
            if (Objects.equals(HoubanYunOrder.getcUpdateFinishTemplateFieldId9(), extend.getWorkStatementTemplateFieldId())) {
                Optional<String> first = extend.getVals().stream().map(FieldValOptionVo::getOptValue).findFirst();
                if (first.isPresent()) {
                    String s = first.get();
                    feildMap.put("2200000500039516", s);
                } else {
                    feildMap.put("2200000500039516", "");
                }
            }
            //新产品CTRI码
            if (Objects.equals(HoubanYunOrder.getcUpdateFinishTemplateFieldId8(), extend.getWorkStatementTemplateFieldId())) {
                Optional<String> first = extend.getVals().stream().map(FieldValOptionVo::getOptValue).findFirst();
                if (first.isPresent()) {
                    String s = first.get();
                    feildMap.put("2200000500022953", s);
                } else {
                    feildMap.put("2200000500022953", "");
                }
            }
        }
        feildMap.put("2200000469555685", CollectionUtil.isEmpty(models) ? "" : String.join(",", models)); // 维修产品型号
        feildMap.put("2200000478776456", CollectionUtil.isEmpty(snCodes) ? "" : String.join("，", snCodes)); // 唯一码/产品SN码
        feildMap.put("2200000469555698", faultResons); // 故障原因
        feildMap.put("2200000469555720", faultDetails); // 故障明细
        feildMap.put("2200000473533605", CollectionUtil.isEmpty(faultImages) ? "" : String.join("，", faultImages)); // 现场故障图片
        feildMap.put("2200000469555722", CollectionUtil.isEmpty(handlerModes) ? "" : String.join(",", handlerModes)); // 解决方式
        feildMap.put("2200000473533606", CollectionUtil.isEmpty(updateAftarImages) ? "" : String.join("，", updateAftarImages)); // 维修后的图片
    }

    /**
     * 获取C端安装工单结单字段
     *
     * @param workId   工单ID
     * @param fieldMap
     */
    private static void getCInstallFinishField(Long workId, Map<String, Object> fieldMap) {
        // 查询安装的结单字段
        List<WorkFinishOrderTemplateFieldValExtend> extendList = lKaiPushService.workFinishOrderTemplateFieldValService.getPushFieldByWorkIdAndWorkStatementTemplateId(workId, HoubanYunOrder.getcInstallFinishTemplateId1());
        List<String> snCodes = new ArrayList<>(); // 唯一码
        List<String> models = new ArrayList<>(); // 产品型号
        List<String> iamges = new ArrayList<>(); // 服务后图片
        List<String> videos=new ArrayList<>();//指静脉使用指导视频
        for (WorkFinishOrderTemplateFieldValExtend extend : extendList) {
            // 产品型号
            if (Objects.equals(HoubanYunOrder.getcInstallFinishTemplateFieldId1(), extend.getWorkStatementTemplateFieldId())) {
                models.addAll(extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList());
            }
            // 唯一码
            if (Objects.equals(HoubanYunOrder.getcInstallFinishTemplateFieldId2(), extend.getWorkStatementTemplateFieldId())) {
                snCodes.addAll(extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList());
            }
            // 维修后图片
            if (Objects.equals(HoubanYunOrder.getcInstallFinishTemplateFieldId3(), extend.getWorkStatementTemplateFieldId())) {
                iamges.addAll(extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList());
            }
            if(Objects.equals(HoubanYunOrder.getcInstallFinishTemplateFieldId4(),extend.getWorkStatementTemplateFieldId())){
                videos.addAll(extend.getVals().stream().map(FieldValOptionVo::getOptValue).toList());
            }
        }
        fieldMap.put("2200000473533606", CollectionUtil.isEmpty(iamges) ? "" : String.join("，", iamges)); // 服务后图片
        fieldMap.put("2200000478776456", CollectionUtil.isEmpty(snCodes) ? "" : String.join("，", snCodes)); // 唯一码/产品SN码
        fieldMap.put("2200000478776708", CollectionUtil.isEmpty(models) ? "" : String.join("，", models)); // 产品型号
        fieldMap.put("2200000504734623",CollectionUtil.isEmpty(videos)?"" :String.join("，", videos));
    }


}
